var express = require('express')
var router = express.Router()
var User = require('../models/User')

// 同意返回格式
var responseData;
router.use( function(request, response, next) {
    
    responseData = {
        code: 0,
        message: ''
    }
    next()
})

router.get('/user', function(req, res, next) {
    res.send('API - user')
})

router.post('/user/register', function (request, response, next) {
    console.log("/user/register", request.body)

    var { username, password, repassword } = request.body
    // var username = request.body.username
    // var password = request.body.password
    // var repassword = request.body.repassword

    if (username == '') {
        responseData.code = 1;
        responseData.message = '用户名不能为空'
        response.json(responseData)
        return
    }

    if (password == '') {
        responseData.code = 2
        responseData.message = '密码不能为空'
        response.json(responseData)
        return
    }

    if (password != repassword) {
        responseData.code = 3
        responseData.message = '两次输入的密码不一致'
        response.json(responseData)
        return
    }

    // 检测是否已经存在
    User.findOne({
        username: username
    }).then(function(userinfo) {
        console.log(userinfo)
        if (userinfo) {
            responseData.code = 4
            responseData.message = '用户名已经被注册了'
            response.json(responseData)
            return
        }

        var user = new User({
            username: username,
            password: password
        })
        return user.save()
    }).then(function(newUserInfo) {
        console.log(newUserInfo)
        responseData.message = '注册成功'
        responseData.user = {
            username: newUserInfo.username,
            password: newUserInfo.password,
            id: newUserInfo._id
        }
        response.json(responseData)
    })  
})

router.post('/user/login', function(request, response, next) {
    var { username, password } = request.body

    if (username == '' || password == '') {
        responseData.code = 1
        responseData.message= '用户名和密码不能为空'
        response.json(responseData)
        return
    }
    User.findOne({
        username: username,
        password: password
    }).then(function(userInfo) {
        if (!userInfo) {
            responseData.code    = 2
            responseData.message = "用户名或密码不正确"
            response.json(responseData)
            return   
        }
        responseData.message = "登录成功"
        var user = {
            username: userInfo.username,
            id: userInfo._id
        }
        responseData.user = user
        request.cookies.set('userInfo', JSON.stringify(user))
        console.log(responseData)
        response.json(responseData)
    })
})

router.get('/user/logout', function(request, response, next) {
    request.cookies.set('userInfo', null);
    responseData.message = '退出'
    response.json(responseData)
})

module.exports = router